<template>
  <div class="tables-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <div class="header-icon">
          <el-icon><Grid /></el-icon>
        </div>
        <div class="header-content">
          <h1>台球桌管理</h1>
          <p>智能管理台球桌状态、价格和维护信息</p>
        </div>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          size="large"
          @click="addTable"
          class="action-btn primary-btn"
        >
          <el-icon><Plus /></el-icon>
          <span>添加台球桌</span>
        </el-button>
        <el-button
          size="large"
          @click="refreshTables"
          class="action-btn refresh-btn"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          <span>刷新数据</span>
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-row">
      <div class="stat-card total-card" @click="filterStatus = ''">
        <div class="stat-content">
          <div class="stat-icon total">
            <el-icon><Grid /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ tableStats.total }}</div>
            <div class="stat-label">总台球桌</div>
            <div class="stat-trend">
              <span class="trend-text">全部台球桌</span>
            </div>
          </div>
        </div>
        <div class="stat-decoration"></div>
      </div>

      <div class="stat-card available-card" @click="filterStatus = 'available'">
        <div class="stat-content">
          <div class="stat-icon available">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ tableStats.available }}</div>
            <div class="stat-label">可用台球桌</div>
            <div class="stat-trend">
              <span class="trend-text">立即可用</span>
            </div>
          </div>
        </div>
        <div class="stat-decoration"></div>
      </div>

      <div class="stat-card occupied-card" @click="filterStatus = 'occupied'">
        <div class="stat-content">
          <div class="stat-icon occupied">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ tableStats.occupied }}</div>
            <div class="stat-label">使用中</div>
            <div class="stat-trend">
              <span class="trend-text">正在使用</span>
            </div>
          </div>
        </div>
        <div class="stat-decoration"></div>
      </div>

      <div class="stat-card maintenance-card" @click="filterStatus = 'maintenance'">
        <div class="stat-content">
          <div class="stat-icon maintenance">
            <el-icon><Tools /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ tableStats.maintenance }}</div>
            <div class="stat-label">维护中</div>
            <div class="stat-trend">
              <span class="trend-text">暂停服务</span>
            </div>
          </div>
        </div>
        <div class="stat-decoration"></div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-card">
        <div class="filter-header">
          <div class="filter-title">
            <el-icon><Search /></el-icon>
            <span>筛选与搜索</span>
          </div>
          <div class="filter-actions">
            <el-button
              text
              @click="resetFilters"
              class="reset-btn"
            >
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>

        <div class="filter-content">
          <div class="filter-group">
            <label class="filter-label">状态筛选</label>
            <el-select
              v-model="filterStatus"
              placeholder="选择状态"
              clearable
              @change="handleFilter"
              class="filter-select"
            >
              <el-option label="全部状态" value="" />
              <el-option label="🟢 可用" value="available" />
              <el-option label="🟡 使用中" value="occupied" />
              <el-option label="🔴 维护中" value="maintenance" />
            </el-select>
          </div>

          <div class="filter-group">
            <label class="filter-label">类型筛选</label>
            <el-select
              v-model="filterType"
              placeholder="选择类型"
              clearable
              @change="handleFilter"
              class="filter-select"
            >
              <el-option label="全部类型" value="" />
              <el-option label="🎱 斯诺克" value="斯诺克" />
              <el-option label="🎯 美式8球" value="美式台球" />
              <el-option label="⚪ 开伦" value="carom" />
            </el-select>
          </div>

          <div class="filter-group search-group">
            <label class="filter-label">快速搜索</label>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索台球桌编号、名称或位置..."
              clearable
              class="search-input"
            >
              <template #prefix>
                <el-icon class="search-icon"><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </div>

    <!-- 台球桌列表 -->
    <div class="table-section">
      <div class="table-header">
        <div class="table-title">
          <h3>台球桌列表</h3>
          <span class="table-count">共 {{ filteredTables.length }} 张台球桌</span>
        </div>
        <div class="table-actions">
          <el-button-group>
            <el-button
              :type="viewMode === 'table' ? 'primary' : ''"
              @click="viewMode = 'table'"
              size="small"
            >
              <el-icon><Grid /></el-icon>
              表格视图
            </el-button>
            <el-button
              :type="viewMode === 'card' ? 'primary' : ''"
              @click="viewMode = 'card'"
              size="small"
            >
              <el-icon><Grid /></el-icon>
              卡片视图
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 表格视图 -->
      <div v-if="viewMode === 'table'" class="table-view">
        <el-table
          :data="filteredTables"
          v-loading="loading"
          class="modern-table"
          :header-cell-style="{ background: '#f8fafc', color: '#374151', fontWeight: '600' }"
          :row-style="{ transition: 'all 0.3s ease' }"
        >
          <el-table-column prop="id" label="编号" width="100%" align="center">
            <template #default="scope">
              <div class="table-id">{{ scope.row.id }}</div>
            </template>
          </el-table-column>

          <el-table-column prop="name" label="台球桌信息" width="200">
            <template #default="scope">
              <div class="table-info">
                <div class="table-name">{{ scope.row.name }}</div>
                <div class="table-location">📍 {{ scope.row.location }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="type" label="类型" width="120" align="center">
            <template #default="scope">
              <el-tag
                :type="getTypeTagType(scope.row.type)"
                class="type-tag"
                effect="light"
              >
                {{ getTypeIcon(scope.row.type) }} {{ getTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="120" align="center">
            <template #default="scope">
              <div class="status-indicator">
                <div :class="['status-dot', scope.row.status]"></div>
                <span class="status-text">{{ getStatusText(scope.row.status) }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="hourlyRate" label="费用" width="100" align="center">
            <template #default="scope">
              <div class="price-info">
                <span class="price">¥{{ scope.row.hourlyRate || 0 }}</span>
                <span class="price-unit">/小时</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="currentUser" label="使用状态" width="150">
            <template #default="scope">
              <div v-if="scope.row.currentUser" class="usage-info">
                <div class="usage-status">{{ scope.row.currentUser }}</div>
                <div v-if="scope.row.startTime" class="usage-time">
                  {{ formatTime(scope.row.startTime) }}
                </div>
              </div>
              <span v-else class="text-muted">空闲中</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="300" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="small"
                  @click="editTable(scope.row)"
                  class="action-btn"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>

                <el-button
                  v-if="scope.row.status === 'occupied'"
                  type="warning"
                  size="small"
                  @click="endSession(scope.row)"
                  class="action-btn"
                >
                  <el-icon><CircleClose /></el-icon>
                  结束使用
                </el-button>

                <el-button
                  v-if="scope.row.status === 'available'"
                  type="info"
                  size="small"
                  @click="startMaintenance(scope.row)"
                  class="action-btn"
                >
                  <el-icon><Tools /></el-icon>
                  维护
                </el-button>

                <el-button
                  v-if="scope.row.status === 'maintenance'"
                  type="success"
                  size="small"
                  @click="endMaintenance(scope.row)"
                  class="action-btn"
                >
                  <el-icon><Check /></el-icon>
                  完成维护
                </el-button>

                <el-button
                  type="danger"
                  size="small"
                  @click="deleteTableAction(scope.row)"
                  class="action-btn"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <div class="cards-grid">
          <div
            v-for="table in filteredTables"
            :key="table.id"
            class="table-card"
            :class="[`status-${table.status}`]"
          >
            <div class="card-header">
              <div class="card-title">
                <span class="table-name">{{ table.name }}</span>
                <span class="table-id">#{{ table.id }}</span>
              </div>
              <div class="card-status">
                <div :class="['status-dot', table.status]"></div>
                <span class="status-text">{{ getStatusText(table.status) }}</span>
              </div>
            </div>

            <div class="card-content">
              <div class="card-info-row">
                <span class="info-label">类型</span>
                <span class="info-value">{{ getTypeIcon(table.type) }} {{ getTypeText(table.type) }}</span>
              </div>
              <div class="card-info-row">
                <span class="info-label">位置</span>
                <span class="info-value">📍 {{ table.location }}</span>
              </div>
              <div class="card-info-row">
                <span class="info-label">费用</span>
                <span class="info-value price">¥{{ table.hourlyRate || 0 }}/小时</span>
              </div>
              <div v-if="table.currentUser" class="card-info-row">
                <span class="info-label">状态</span>
                <span class="info-value">{{ table.currentUser }}</span>
              </div>
            </div>

            <div class="card-actions">
              <el-button
                type="primary"
                size="small"
                @click="editTable(table)"
                class="card-action-btn"
              >
                <el-icon><Edit /></el-icon>
              </el-button>

              <el-button
                v-if="table.status === 'occupied'"
                type="warning"
                size="small"
                @click="endSession(table)"
                class="card-action-btn"
              >
                <el-icon><CircleClose /></el-icon>
              </el-button>

              <el-button
                v-if="table.status === 'available'"
                type="info"
                size="small"
                @click="startMaintenance(table)"
                class="card-action-btn"
              >
                <el-icon><Tools /></el-icon>
              </el-button>

              <el-button
                v-if="table.status === 'maintenance'"
                type="success"
                size="small"
                @click="endMaintenance(table)"
                class="card-action-btn"
              >
                <el-icon><Check /></el-icon>
              </el-button>

              <el-button
                type="danger"
                size="small"
                @click="deleteTableAction(table)"
                class="card-action-btn"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑台球桌对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑台球桌' : '添加台球桌'"
      width="650px"
      class="modern-dialog"
      :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <el-form
          :model="tableForm"
          :rules="tableRules"
          ref="tableFormRef"
          label-width="120px"
          class="modern-form"
        >
          <div class="form-section">
            <h4 class="section-title">基本信息</h4>

            <el-form-item label="台球桌名称" prop="name">
              <el-input
                v-model="tableForm.name"
                placeholder="请输入台球桌名称"
                size="large"
                class="form-input"
              >
                <template #prefix>
                  <el-icon><Grid /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="台球桌类型" prop="type">
              <el-select
                v-model="tableForm.type"
                placeholder="请选择台球桌类型"
                size="large"
                class="form-select"
              >
                <el-option label="🎱 斯诺克" value="snooker" />
                <el-option label="🎯 美式8球" value="pool" />
                <el-option label="⚪ 开伦" value="carom" />
              </el-select>
            </el-form-item>

            <el-form-item label="位置信息" prop="location">
              <el-input
                v-model="tableForm.location"
                placeholder="请输入位置信息，如：一楼A区"
                size="large"
                class="form-input"
              >
                <template #prefix>
                  <el-icon>📍</el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>

          <div class="form-section">
            <h4 class="section-title">价格设置</h4>

            <el-form-item label="小时费用" prop="hourlyRate">
              <el-input-number
                v-model="tableForm.hourlyRate"
                :min="1"
                :max="1000"
                :precision="0"
                controls-position="right"
                size="large"
                class="form-number"
              />
              <span class="form-hint">元/小时</span>
            </el-form-item>
          </div>

          <div class="form-section">
            <h4 class="section-title">其他信息</h4>

            <el-form-item label="描述信息" prop="description">
              <el-input
                v-model="tableForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入台球桌的详细描述信息，如设备状况、特色等..."
                class="form-textarea"
              />
            </el-form-item>
          </div>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            size="large"
            @click="dialogVisible = false"
            class="cancel-btn"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            size="large"
            @click="saveTable"
            :loading="saving"
            class="save-btn"
          >
            <el-icon v-if="!saving"><Check /></el-icon>
            {{ isEdit ? '更新台球桌' : '添加台球桌' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTables, createTable, updateTable, deleteTable, updateTableStatus } from '../../api/table';
import { getBookedSlots } from '../../api/order';
import {
  Plus,
  Refresh,
  Grid,
  Check,
  User,
  Tools,
  Search,
  Edit,
  Delete,
  CircleClose
} from '@element-plus/icons-vue';

export default {
  name: 'Tables',
  components: {
    Plus,
    Refresh,
    Grid,
    Check,
    User,
    Tools,
    Search,
    Edit,
    Delete,
    CircleClose
  },
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const isEdit = ref(false);
    const saving = ref(false);
    const tableFormRef = ref();

    const filterStatus = ref('');
    const filterType = ref('');
    const searchKeyword = ref('');
    const viewMode = ref('table'); // 'table' 或 'card'

    // 台球桌数据
    const tables = ref([]);

    // 表单数据
    const tableForm = reactive({
      id: null,
      name: '',
      type: '',
      location: '',
      hourlyRate: 30,
      description: '',
      status: 'available'
    });

    // 表单验证规则
    const tableRules = {
      name: [
        { required: true, message: '请输入台球桌名称', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择台球桌类型', trigger: 'change' }
      ],
      location: [
        { required: true, message: '请输入位置信息', trigger: 'blur' }
      ],
      hourlyRate: [
        { required: true, message: '请输入小时费用', trigger: 'blur' }
      ]
    };

    // 计算属性
    const tableStats = computed(() => {
      const total = tables.value.length;
      const available = tables.value.filter(t => t.status === 'available').length;
      const occupied = tables.value.filter(t => t.status === 'occupied').length;
      const maintenance = tables.value.filter(t => t.status === 'maintenance').length;

      return { total, available, occupied, maintenance };
    });

    const filteredTables = computed(() => {
      let result = tables.value;

      // 状态筛选
      if (filterStatus.value) {
        result = result.filter(table => table.status === filterStatus.value);
      }

      // 类型筛选
      if (filterType.value) {
        result = result.filter(table => table.type === filterType.value);
      }

      // 关键词搜索
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase();
        result = result.filter(table =>
          (table.name || '').toLowerCase().includes(keyword) ||
          (table.location || '').toLowerCase().includes(keyword) ||
          (table.id || '').toString().includes(keyword)
        );
      }

      return result;
    });

    // 方法
    const loadTables = async () => {
      loading.value = true;
      try {
        const response = await getTables();
        if (response.success) {
          // 处理后端返回的数据格式：{success: true, data: {items: [...], total: 8}}
          let tablesData = [];
          if (Array.isArray(response.data)) {
            tablesData = response.data;
          } else if (response.data && Array.isArray(response.data.items)) {
            tablesData = response.data.items;
          } else if (response.data && Array.isArray(response.data.tables)) {
            tablesData = response.data.tables;
          } else {
            console.error('无法解析台球桌数据:', response.data);
            ElMessage.error('台球桌数据格式错误');
            return;
          }

          // 转换数据格式以匹配前端显示
          tables.value = await Promise.all(tablesData.map(async table => {
            // 获取当前台球桌的使用状态
            let currentUser = null;
            let startTime = null;

            try {
              // 获取今天的已预订时间段
              const today = new Date().toISOString().split('T')[0];
              const slotsResponse = await getBookedSlots(table.id, today);

              if (slotsResponse.success && slotsResponse.data.length > 0) {
                // 查找当前时间段内的订单
                const now = new Date();
                const currentHour = now.getHours();
                const currentMinute = now.getMinutes();
                const currentTimeStr = `${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`;

                const activeOrder = slotsResponse.data.find(slot => {
                  if (slot.status === 'using' || slot.status === 'paid') {
                    const startTime = slot.start_time;
                    const endTime = slot.end_time;
                    return currentTimeStr >= startTime && currentTimeStr <= endTime;
                  }
                  return false;
                });

                if (activeOrder) {
                  currentUser = '使用中';
                  startTime = activeOrder.start_time;
                  // 更新台球桌状态为使用中
                  table.status = 'occupied';
                }
              }
            } catch (error) {
              console.error('获取台球桌使用状态失败:', error);
            }

            return {
              id: table.id || 0,
              name: table.name || '未命名',
              type: table.type || 'pool',
              status: table.status || 'available',
              location: table.location || '未设置',
              hourlyRate: Number(table.hourly_rate) || 30,
              description: table.description || '',
              currentUser,
              startTime,
              lastMaintenance: null
            };
          }));
        } else {
          ElMessage.error('加载台球桌数据失败');
        }
      } catch (error) {
        console.error('加载台球桌数据失败:', error);
        ElMessage.error('加载台球桌数据失败');
      } finally {
        loading.value = false;
      }
    };

    const refreshTables = () => {
      loadTables();
      ElMessage.success('数据刷新成功');
    };

    const addTable = () => {
      isEdit.value = false;
      Object.assign(tableForm, {
        id: null,
        name: '',
        type: '',
        location: '',
        hourlyRate: 30,
        description: '',
        status: 'available'
      });
      dialogVisible.value = true;
    };

    const editTable = (table) => {
      isEdit.value = true;
      Object.assign(tableForm, { ...table });
      dialogVisible.value = true;
    };

    const saveTable = async () => {
      try {
        await tableFormRef.value.validate();
        saving.value = true;

        // 准备API数据格式
        const apiData = {
          name: tableForm.name,
          type: tableForm.type,
          location: tableForm.location,
          hourly_rate: tableForm.hourlyRate,
          description: tableForm.description
        };

        if (isEdit.value) {
          // 更新台球桌
          const response = await updateTable(tableForm.id, apiData);
          if (response.success) {
            ElMessage.success('台球桌更新成功');
            await loadTables(); // 重新加载数据
          } else {
            ElMessage.error(response.message || '更新失败');
            return;
          }
        } else {
          // 添加台球桌
          const response = await createTable(apiData);
          if (response.success) {
            ElMessage.success('台球桌添加成功');
            await loadTables(); // 重新加载数据
          } else {
            ElMessage.error(response.message || '添加失败');
            return;
          }
        }

        dialogVisible.value = false;
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败，请重试');
      } finally {
        saving.value = false;
      }
    };

    const deleteTableAction = async (table) => {
      try {
        await ElMessageBox.confirm(
          `确认删除台球桌 "${table.name}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        const response = await deleteTable(table.id);
        if (response.success) {
          ElMessage.success('台球桌删除成功');
          await loadTables(); // 重新加载数据
        } else {
          ElMessage.error(response.message || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          ElMessage.error('删除失败，请重试');
        }
      }
    };

    const endSession = async (table) => {
      try {
        await ElMessageBox.confirm(
          `确认结束 "${table.name}" 的使用吗？`,
          '结束使用',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        const response = await updateTableStatus(table.id, 'available');
        if (response.success) {
          ElMessage.success('使用已结束');
          await loadTables(); // 重新加载数据
        } else {
          ElMessage.error(response.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('操作失败:', error);
          ElMessage.error('操作失败，请重试');
        }
      }
    };

    const startMaintenance = async (table) => {
      try {
        await ElMessageBox.confirm(
          `确认将 "${table.name}" 设置为维护状态吗？`,
          '开始维护',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        const response = await updateTableStatus(table.id, 'maintenance');
        if (response.success) {
          ElMessage.success('已设置为维护状态');
          await loadTables(); // 重新加载数据
        } else {
          ElMessage.error(response.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('操作失败:', error);
          ElMessage.error('操作失败，请重试');
        }
      }
    };

    const endMaintenance = async (table) => {
      try {
        await ElMessageBox.confirm(
          `确认完成 "${table.name}" 的维护吗？`,
          '完成维护',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'info'
          }
        );

        const response = await updateTableStatus(table.id, 'available');
        if (response.success) {
          ElMessage.success('维护已完成');
          await loadTables(); // 重新加载数据
        } else {
          ElMessage.error(response.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('操作失败:', error);
          ElMessage.error('操作失败，请重试');
        }
      }
    };

    const handleFilter = () => {
      // 筛选逻辑已在计算属性中处理
    };

    const resetFilters = () => {
      filterStatus.value = '';
      filterType.value = '';
      searchKeyword.value = '';
      ElMessage.success('筛选条件已重置');
    };

    // 辅助方法
    const getStatusText = (status) => {
      const statusMap = {
        available: '可用',
        occupied: '使用中',
        maintenance: '维护中'
      };
      return statusMap[status] || '未知';
    };

    const getStatusTagType = (status) => {
      const typeMap = {
        available: 'success',
        occupied: 'warning',
        maintenance: 'danger'
      };
      return typeMap[status] || 'info';
    };

    const getTypeText = (type) => {
      const typeMap = {
        snooker: '斯诺克',
        pool: '美式8球',
        carom: '开伦'
      };
      return typeMap[type] || '未知';
    };

    const getTypeTagType = (type) => {
      const typeMap = {
        snooker: '',
        pool: 'warning',
        carom: 'danger'
      };
      return typeMap[type] || 'info';
    };

    const getTypeIcon = (type) => {
      const iconMap = {
        snooker: '🎱',
        pool: '🎯',
        carom: '⚪'
      };
      return iconMap[type] || '🎱';
    };

    const formatTime = (timeStr) => {
      if (!timeStr) return '';
      return new Date(timeStr).toLocaleString('zh-CN');
    };

    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      return new Date(dateStr).toLocaleDateString('zh-CN');
    };

    const resetForm = () => {
      Object.assign(tableForm, {
        id: null,
        name: '',
        type: '',
        location: '',
        hourlyRate: 30,
        description: '',
        status: 'available'
      });
    };

    // 组件挂载时加载数据
    onMounted(async () => {
      try {
        await loadTables();
      } catch (error) {
        console.error('台球桌管理页面初始化失败:', error);
        ElMessage.error('页面初始化失败，请刷新重试');
      }
    });

    return {
      loading,
      dialogVisible,
      isEdit,
      saving,
      tableFormRef,
      filterStatus,
      filterType,
      searchKeyword,
      viewMode,
      tables,
      tableForm,
      tableRules,
      tableStats,
      filteredTables,
      loadTables,
      refreshTables,
      addTable,
      editTable,
      saveTable,
      deleteTableAction,
      endSession,
      startMaintenance,
      endMaintenance,
      handleFilter,
      resetFilters,
      resetForm,
      getStatusText,
      getStatusTagType,
      getTypeText,
      getTypeTagType,
      getTypeIcon,
      formatTime,
      formatDate,
      Plus,
      Refresh,
      Grid,
      Check,
      User,
      Tools,
      Search,
      Edit,
      Delete,
      CircleClose
    };
  }
};
</script>

<style scoped>
.tables-container {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  color: white;
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  transform: translate(50%, -50%);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
  z-index: 1;
}

.header-icon {
  width: 64px;
  height: 64px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  backdrop-filter: blur(10px);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 16px;
  z-index: 1;
}

.action-btn {
  border: none !important;
  border-radius: 12px !important;
  padding: 12px 12px !important;
  font-weight: 600 !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px);
}

.primary-btn {
  background: rgba(255, 255, 255, 0.2) !important;
  color: white !important;
}

.primary-btn:hover {
  background: rgba(255, 255, 255, 0.3) !important;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.refresh-btn {
  background: rgba(255, 255, 255, 0.1) !important;
  color: white !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
}

.refresh-btn:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  transform: translateY(-2px);
}

/* 统计卡片 */
.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 2px solid transparent;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.stat-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  border-color: rgba(102, 126, 234, 0.3);
}

.stat-decoration {
  position: absolute;
  top: -20px;
  right: -20px;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  opacity: 0.1;
}

.total-card .stat-decoration {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.available-card .stat-decoration {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.occupied-card .stat-decoration {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.maintenance-card .stat-decoration {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-content {
  display: flex;
  align-items: center;
  position: relative;
  z-index: 1;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 28px;
  color: white;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.available {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.stat-icon.occupied {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.stat-icon.maintenance {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 36px;
  font-weight: 800;
  color: #2c3e50;
  margin-bottom: 4px;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #64748b;
  font-weight: 600;
  margin-bottom: 4px;
}

.stat-trend {
  margin-top: 8px;
}

.trend-text {
  font-size: 12px;
  color: #94a3b8;
  background: #f1f5f9;
  padding: 4px 8px;
  border-radius: 8px;
  font-weight: 500;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 32px;
}

.filter-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.filter-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.filter-title .el-icon {
  color: #667eea;
}

.reset-btn {
  color: #64748b !important;
  font-size: 14px !important;
}

.reset-btn:hover {
  color: #667eea !important;
}

.filter-content {
  display: grid;
  grid-template-columns: 1fr 1fr 2fr;
  gap: 24px;
  align-items: end;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.filter-select {
  width: 100%;
}

.search-group {
  position: relative;
}

.search-input {
  width: 100%;
}

.search-icon {
  color: #9ca3af;
}

/* 表格区域 */
.table-section {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.table-title h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 700;
  color: #1e293b;
}

.table-count {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.table-actions .el-button-group .el-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
}

/* 表格视图 */
.table-view {
  width: 100%;
  /* margin-top: 16px; */
}

.modern-table {
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.table-id {
  font-weight: 700;
  color: #667eea;
  background: #f0f4ff;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
}

.table-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.table-name {
  font-weight: 600;
  color: #1e293b;
  font-size: 16px;
}

.table-location {
  font-size: 14px;
  color: #64748b;
}

.type-tag {
  font-weight: 600 !important;
  border-radius: 8px !important;
  padding: 4px 12px !important;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  position: relative;
}

.status-dot.available {
  background: #10b981;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);
}

.status-dot.occupied {
  background: #f59e0b;
  box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.2);
}

.status-dot.maintenance {
  background: #ef4444;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.2);
}

.status-dot.available::after,
.status-dot.occupied::after,
.status-dot.maintenance::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: white;
  transform: translate(-50%, -50%);
}

.status-text {
  font-weight: 600;
  font-size: 14px;
}

.price-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.price {
  font-weight: 700;
  color: #059669;
  font-size: 16px;
}

.price-unit {
  font-size: 12px;
  color: #64748b;
}

.usage-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.usage-status {
  font-weight: 600;
  color: #1e293b;
  font-size: 14px;
}

.usage-time {
  font-size: 12px;
  color: #64748b;
}

.text-muted {
  color: #9ca3af;
  font-style: italic;
}

.action-buttons {
  display: flex;
}

.action-btn {
  border-radius: 8px !important;
  font-weight: 500 !important;
  transition: all 0.2s ease !important;
}

.action-btn:hover {
  transform: translateY(-1px);
}

/* 卡片视图 */
.card-view {
  margin-top: 16px;
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.table-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  border: 2px solid #e2e8f0;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.table-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
  border-color: #667eea;
}

.table-card.status-available {
  border-left: 4px solid #10b981;
}

.table-card.status-occupied {
  border-left: 4px solid #f59e0b;
}

.table-card.status-maintenance {
  border-left: 4px solid #ef4444;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.card-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.card-title .table-name {
  font-size: 18px;
  font-weight: 700;
  color: #1e293b;
}

.card-title .table-id {
  font-size: 12px;
  font-weight: 600;
  color: #667eea;
  background: #f0f4ff;
  padding: 2px 8px;
  border-radius: 6px;
  align-self: flex-start;
}

.card-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.card-content {
  margin-bottom: 20px;
}

.card-info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f1f5f9;
}

.card-info-row:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #1e293b;
  font-weight: 600;
}

.info-value.price {
  color: #059669;
  font-weight: 700;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.card-action-btn {
  flex: 1;
  min-width: 40px;
  border-radius: 8px !important;
  font-weight: 500 !important;
  transition: all 0.2s ease !important;
}

.card-action-btn:hover {
  transform: translateY(-1px);
}

/* 对话框样式 */
.modern-dialog {
  border-radius: 20px !important;
}

.dialog-content {
  padding: 8px 0;
}

.modern-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 8px;
}

.form-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f1f5f9;
}

.form-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 700;
  color: #1e293b;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 16px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 2px;
}

.form-input,
.form-select,
.form-number,
.form-textarea {
  border-radius: 12px !important;
  border: 2px solid #e2e8f0 !important;
  transition: all 0.3s ease !important;
}

.form-input:focus,
.form-select:focus,
.form-number:focus,
.form-textarea:focus {
  border-color: #667eea !important;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1) !important;
}

.form-hint {
  margin-left: 12px;
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  gap: 16px;
  justify-content: flex-end;
  padding-top: 24px;
  border-top: 1px solid #f1f5f9;
}

.cancel-btn {
  border-radius: 12px !important;
  padding: 12px 24px !important;
  font-weight: 600 !important;
  border: 2px solid #e2e8f0 !important;
  color: #64748b !important;
}

.cancel-btn:hover {
  border-color: #cbd5e1 !important;
  color: #475569 !important;
}

.save-btn {
  border-radius: 12px !important;
  padding: 12px 24px !important;
  font-weight: 600 !important;
  background: linear-gradient(135deg, #667eea, #764ba2) !important;
  border: none !important;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important;
}

.save-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4) !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-row {
    grid-template-columns: repeat(2, 1fr);
  }

  .filter-content {
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }

  .search-group {
    grid-column: 1 / -1;
  }
}

@media (max-width: 768px) {
  .tables-container {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
    padding: 24px;
  }

  .header-left {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .header-actions {
    justify-content: center;
  }

  .stats-row {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .filter-content {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .table-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .cards-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }

  .card-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .header-content h1 {
    font-size: 24px;
  }

  .stat-number {
    font-size: 28px;
  }

  .stat-icon {
    width: 48px;
    height: 48px;
    font-size: 20px;
  }
}
</style>
